package com.jdy.hotel.support;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.MutableLiveData;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.jdy.hotel.check.CheckItem;
import com.jdy.hotel.net.ResponseData;
import com.jdy.hotel.support.view.ControlViewPager;
import com.jdy.hotel.support.view.IView;
import com.jdy.hotel.utils.L;
import com.jdy.hotel.utils.StatusBarUtil;

import org.jetbrains.annotations.NotNull;

import java.util.List;

public abstract class BaseActivity extends AppCompatActivity {

    protected ProgressBar loadingProgressBar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutSource());

        StatusBarUtil.setCommonUI(this, true);

        createView(savedInstanceState);

        bindModel();

        setListeners();

        bindData(savedInstanceState);
    }

    protected abstract int getLayoutSource();

    protected void createView(Bundle savedInstanceState) {
    }

    protected void bindModel() {
    }

    protected void setListeners() {
    }

    protected void bindData(Bundle savedInstanceState) {
    }

    /**
     * 初始化ViewPager
     *
     * @param viewPager ViewPager 对象
     * @param views     ViewPager中的View
     */
    protected void initViewPager(ControlViewPager viewPager, final IView... views) {
        viewPager.setOffscreenPageLimit(views.length);
        setViewPager(viewPager);
        viewPager.setAdapter(createViewPagerAdapter(views));

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {
            }

            @Override
            public void onPageSelected(int i) {
                onPageChange(views[i]);
            }

            @Override
            public void onPageScrollStateChanged(int i) {
            }
        });
    }

    protected void setViewPager(ViewPager viewPager) {

    }

    protected PagerAdapter createViewPagerAdapter(final IView... views) {
        return new PagerAdapter() {
            @Override
            public int getCount() {
                return views.length;
            }

            @Override
            public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
                if (object instanceof IView)
                    return view == ((IView) object).getView();
                if (object instanceof View)
                    return view == object;
                return false;
            }

            @NonNull
            @Override
            public Object instantiateItem(@NonNull ViewGroup container, int position) {
                container.addView(views[position].getView());
                return views[position].getView();
            }

            @Override
            public void destroyItem(@NotNull ViewGroup container, int position, @NotNull Object object) {
                View view = views[position].getView();
                if (view != null)
                    container.removeView(view);
            }

            @Override
            public int getItemPosition(@NonNull Object object) {
                if (object instanceof View) {
                    View currentView = (View) object;
                    for (int i = 0; i < views.length; i++) {
                        View view = views[i].getView();
                        if (view.findViewById(currentView.getId()) != null) return i;
                    }
                }
                return super.getItemPosition(object);
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return views[position].getTitle();
            }
        };
    }


    protected void setFormObserver(MutableLiveData<ResponseData> formData) {
        formData.observe(this, result -> {
            if (result == null) {
                return;
            }
            if (loadingProgressBar != null) loadingProgressBar.setVisibility(View.GONE);
//            L.i("校验结果： %s ", result);
            if (result.isSuccess())
                onValidSuccess(result);
            else { //输入校验结果
                Object data = result.getData();

                if (data == null) return;

                if (data instanceof List) {
                    for (Object value : ((List) data)) {
                        handleError(value, result.getMessage());
                    }
                    return;
                }
                handleError(data, result.getMessage());
            }
        });
    }

    protected void onValidSuccess(ResponseData result) {

    }

    protected void setRequestObserver(MutableLiveData<ResponseData> responseData) {
        responseData.observe(this, response -> {
            if (response == null) {
                return;
            }
            L.i("请求响应的结果： %s ", response);
            if (loadingProgressBar != null) loadingProgressBar.setVisibility(View.GONE);
            if (response.isSuccess())
                onRespond(response);
            else if (response.getCode() == ResponseData.DEFAULT_REQUEST_ERROR_CODE)
                showMessage(response.getMessage());//响应码为400的数据，弹出提示，否则需要处理
            else
                onFailure(response);//APP应用异常
        });
    }

    /**
     * 网络请求失败时调用
     *
     * @param response 请求成功结果
     */
    protected void onRespond(ResponseData response) {

    }

    /**
     * 网络请求失败时调用
     *
     * @param response 请求失败结果
     */
    protected void onFailure(ResponseData response) {

    }

    /**
     * 当页面进行跳转时调用
     *
     * @param view View的包装器
     */
    protected void onPageChange(IView view) {

    }

    /**
     * 表单校验出错误时调用
     *
     * @param o       错误消息载体
     * @param message 错误消息内容
     */
    private void handleError(Object o, String message) {
        if (o instanceof CheckItem) {
            CheckItem errorItem = (CheckItem) o;
            View view = errorItem.getView();
            if (view instanceof TextView) {
                ((TextView) view).setError(message += " : " + errorItem.getMessage());
            }
            onError(view, message);
        }
    }

    /**
     * 继续处理编辑结果,需要调用者自己处理
     *
     * @param o       错误消息载体
     * @param message 错误消息内容
     */
    protected void onError(View o, String message) {

    }


    protected void showMessage(String message) {
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }

}
